<template>
  <c-back-wrap :loading="loading" go-page="经销商门店业务变更" :before-call-back="$goBackCall" :current-page="currentPage">
    <c-title title="经销商-客户基本信息">
      <CusetomerBaseInfo ref="cusetomerBaseInfoForm" v-model="cusetomerBaseInfoFormData" :disabled="isEdit" :detail="detail" @change="handleCustomerChange" />
    </c-title>
    <c-title title="经销商-选择待变更门店">
      <ChangeTable v-model="changeResultTableData" :table-data="changeTableData" />
    </c-title>
    <c-title title="经销商-门店业务类型变更信息">
      <!-- <el-collapse v-if="raw_changeTableData.length>0" v-model="activeName"> -->
      <c-collapse-item v-for="(d,i) in changeResultTableData" :key="i" :name="i+1">
        <div slot="title" class="change-table-title">
          <span>{{ d.code }}</span>
          <span>{{ d.name }}</span>
          <span>{{ d.shopAddr }}</span>
        </div>
        <QupFormContainer :column="1">
          <el-form ref="form2" :model="d" :rules="formRules" label-width="140px">
            <template v-if="isAdd">
              <el-form-item prop="afterBusinessType" label="变更后经营业务类型">
                <c-common-search-mdm
                  placeholder="请选择"
                  cust-doc-code="QY037"
                >
                  <template v-slot="data">
                    <el-checkbox-group v-model="d.afterBusinessType" @change="v=>handleBusinessChange(d,data,v)">
                      <el-checkbox v-for="dt in data" :key="dt.code" :label="dt.code" :disabled="(d.businessType || '').includes(dt.code)">{{ dt.name }}</el-checkbox>
                    </el-checkbox-group>
                  </template>
                </c-common-search-mdm>
              </el-form-item>
              <el-form-item prop="isReportPic" label="是否报图">
                <!-- <el-switch v-model="d.isReportPic" :active-value="1" :inactive-value="0" /> -->
                <c-dict-select v-model="d.isReportPic" dict-type-code="BOOLEANS" clearable placeholder="是否报图" />
              </el-form-item>
              <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS065" label="补充协议附件" :span="24">
                <c-file-list v-model="d.ACCESS065" direct-del :model-id="d.id" type-code="ACCESS065" />
              </el-form-item>
              <el-form-item prop="1" label="补充协议模板下载" :span="24">
                <div class="template-down" @click.stop="handleDownTemplate(ACCESS065.id)">
                  <span>下载补充协议模板下载</span>
                  <i class="el-icon-download" />
                </div>
              </el-form-item>
              <el-form-item prop="2" label="补充协议签订说明下载" :span="24">
                <div class="template-down" @click.stop="handleDownTemplate(ACCESS066.id)">
                  <span>下载补充协议签订说明</span>
                  <i class="el-icon-download" />
                </div>
              </el-form-item>
              <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS067" label="特殊建档附件" :span="24">
                <c-file-list v-model="d.ACCESS067" direct-del tip="如未报图/未交保证金等情况，业务请示申请审核通过的流程附件" :model-id="d.id" type-code="ACCESS067" />
              </el-form-item>
            </template>
            <template v-else-if="raw_changeTableData.length>0">
              <el-form-item :key="d.code + d.name" prop="afterBusinessType" label="变更后经营业务类型">
                <c-common-search-mdm
                  placeholder="请选择"
                  cust-doc-code="QY037"
                  :after-response="res=>filterQY037(res,d)"
                >
                  <template v-slot="data">
                    <el-checkbox-group v-model="d.afterBusinessType" @change="v=>handleBusinessChange(d,data,v)">
                      <el-checkbox v-for="dt in data" :key="dt.code" :disabled="cancelDisabled(d, dt.code, data)" :label="dt.code">{{ dt.name }}</el-checkbox>
                    </el-checkbox-group>
                  </template>
                </c-common-search-mdm>
              </el-form-item>
              <el-form-item prop="cancelReason" label="业务类型取消原因">
                <el-input v-model="d.cancelReason" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="业务类型取消原因" />
              </el-form-item>
              <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS068" label="取消业务附件" :span="24">
                <c-file-list v-model="d.ACCESS068" direct-del :model-id="d.id" type-code="ACCESS068" />
              </el-form-item>
            </template>
          </el-form>
        </QupFormContainer>
      </c-collapse-item>
      <!-- </el-collapse> -->
    </c-title>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSave">保存</c-button>
      <c-button type="primary" @click="handleSubmit">提交</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { shopBusinessDetail, shopBusinessSaveOrSubmit } from '@/api/channelTask2/shopChange'
import { shopListByCustomer, getTemplateConfig, downTemplate } from '@/api/channelTask2/change'
import CusetomerBaseInfo from '@/views/channelTask2/dealerMarketingInfo/archive/components/CustomerBaseInfo'
import ChangeTable from '../../components/ChangeTable'

export default {
  name: 'AddEdit',
  components: {
    ChangeTable,
    CusetomerBaseInfo
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    isAdd: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      detail: {},
      loading: false,
      cusetomerBaseInfoFormData: {}, // 经销商-客户基本信息
      formData: {},
      formRules: {
        isReportPic: [{ required: true, message: '请选择是否报图', trigger: 'change' }],
        ACCESS065: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length <= 0) {
            c(new Error('请上传补充协议附件'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        cancelReason: [{ required: true, message: '请输入业务类型取消原因', trigger: 'change' }]
      },
      activeName: 1,
      changeTableData: [],
      raw_changeTableData: [], // 原始副本
      changeResultTableData: [],
      // 模板配置
      ACCESS065: {},
      ACCESS066: {}
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    currentPage() {
      return this.isAdd ? `门店新增业务${this.isEdit ? '编辑' : ''}` : `取消业务${this.isEdit ? '编辑' : ''}`
    }
  },
  created() {
    this.id && this.getDetailData()
    this.templateConfig()
  },
  methods: {
    getDetailData() {
      this.loading = true
      return shopBusinessDetail(this.id).then(res => {
        this.detail = res.data
        this.detail.shopBusinessDTOS.forEach(e => {
          e.afterBusinessTypeName = (e.afterBusinessTypeName || '').split(',')
          e.afterBusinessType = (e.afterBusinessType || '').split(',')
          e.businessType = (e.businessType || '').split(',')
          e.businessTypeName = (e.businessTypeName || '').split(',')
          if (e.isReportPic === undefined) {
            e.isReportPic = ''
          }
        })

        this.changeResultTableData = this.detail.shopBusinessDTOS.filter(e => [1, '1'].includes(e.isChange))

        this.getShopData(this.detail.customerCode)
      }).finally(() => {
        this.loading = false
      })
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    getShopData(customerCode) {
      return shopListByCustomer(customerCode).then(res => {
        const t = res.data.map(e => {
          e.afterBusinessType = (e.businessType || '').split(',')
          e.afterBusinessTypeName = (e.businessTypeName || '').split(',')
          e.businessType = (e.businessType || '').split(',')
          e.businessTypeName = (e.businessTypeName || '').split(',')
          if (e.isReportPic === undefined) {
            e.isReportPic = ''
          }
          return e
        })
        this.raw_changeTableData = t
        this.changeTableData = this.$deepClone(t).map(e => {
          const tmp = this.changeResultTableData.find(ee => ee.code === e.code && ee.name === e.name)
          if (tmp) {
            return tmp
          }
          return e
        })
      })
    },
    handleCustomerChange(customerCode) {
      this.changeResultTableData = []
      this.raw_changeTableData = []
      this.changeTableData = []
      if (customerCode) {
        this.getShopData(customerCode)
      }
    },
    templateConfig() {
      getTemplateConfig('ACCESS065').then(res => {
        this.ACCESS065 = res
      })
      getTemplateConfig('ACCESS066').then(res => {
        this.ACCESS066 = res
      })
    },
    handleDownTemplate(id) {
      downTemplate(id)
    },
    handleBusinessChange(d, data, v) {
      d.afterBusinessTypeName = (data || []).filter(e => v.includes(e.code)).map(e => e.name)
    },
    hasChange() {
      const raw = this.raw_changeTableData
      const result = this.changeResultTableData
      if (result.length <= 0) {
        return false
      }
      for (const r of result) {
        const t = raw.find(e => r.code === e.code && r.name === e.name)
        if (!t) {
          continue
        }

        const r_afterBusinessType = this.$deepClone(r.afterBusinessType)
        r_afterBusinessType.sort()
        const t_afterBusinessType = this.$deepClone(t.afterBusinessType)
        t_afterBusinessType.sort()
        let is_change = r_afterBusinessType.join('') !== t_afterBusinessType.join('')
        is_change = is_change || parseInt(r.isReportPic) !== parseInt(t.isReportPic)
        is_change = is_change || r.cancelReason !== t.cancelReason
        if (!is_change) {
          this.$message.warning(`门店【${r.name}】信息无变更!`)
          return false
        }
      }
      return true
    },
    async validate() {
      await this.$refs.cusetomerBaseInfoForm.validate()
      if (this.$refs.form2 && this.$refs.form2.length > 0) {
        await Promise.all(this.$refs.form2.map(e => e.validate()))
      }
      return new Promise((resolve, reject) => {
        if (!this.hasChange()) {
          return reject(false)
        }
        for (const row of this.changeResultTableData) {
          // 门店XXXX（显示编码）业务类型未变更，请检查
          const businessType = typeof row.businessType === 'string' ? row.businessType.split(',') : row.businessType
          if (businessType.length === row.afterBusinessType.length && row.afterBusinessType.every(e => businessType.includes(e))) {
            const msg = `门店${row.name}（${row.code}）业务类型未变更，请检查!`
            this.$message.warning(msg)
            return reject(msg)
          }
        }
        resolve(true)
      })
    },
    getPostData(isSubmit) {
      const shopBusinessDTOS = this.$deepClone(this.changeResultTableData)
      if (isSubmit) {
        const rawData = this.$deepClone(this.raw_changeTableData).filter(e => !shopBusinessDTOS.some(ee => e.code === ee.code))
        shopBusinessDTOS.push(...rawData)
      }
      const data = {}
      if (this.id) {
        Object.assign(data, this.$deepClone(this.detail))
      }
      Object.assign(data, this.$deepClone(this.cusetomerBaseInfoFormData))
      data.type = this.isAdd ? 'C' : 'D'
      data.shopBusinessDTOS = shopBusinessDTOS.map(e => {
        const t = {
          ...e,
          afterBusinessType: e.afterBusinessType instanceof Array ? e.afterBusinessType.join(',') : e.afterBusinessType,
          afterBusinessTypeName: e.afterBusinessTypeName instanceof Array ? e.afterBusinessTypeName.join(',') : e.afterBusinessTypeName,
          businessType: e.businessType instanceof Array ? e.businessType.join(',') : e.businessType,
          businessTypeName: e.businessTypeName instanceof Array ? e.businessTypeName.join(',') : e.businessTypeName,
          attachmentDTOS: [
            ...this.$getFiles(e.ACCESS065 || []),
            ...this.$getFiles(e.ACCESS067 || []),
            ...this.$getFiles(e.ACCESS068 || [])
          ]
        }
        delete t.ACCESS065
        delete t.ACCESS067
        delete t.ACCESS068
        return t
      })
      return data
    },
    handleSave() {
      const data = this.getPostData()
      data.schedule = 'A'
      return shopBusinessSaveOrSubmit(data).then(res => {
        this.$message.success('操作成功!')
        this.$pageStack.pop('onPage')
      })
    },
    handleSubmit() {
      return this.validate().then(() => {
        const data = this.getPostData(true)
        data.schedule = 'B'
        return shopBusinessSaveOrSubmit(data).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    filterQY037(response, d) {
      const t = this.raw_changeTableData.find(e => e.code === d.code && e.name === d.name)
      if (t) {
        response.data.data.records = response.data.data.records.filter(e => t.afterBusinessType.includes(e.code))
      }
      return response
    },
    // 取消业务 必须要有一个类型
    cancelDisabled(d, code, data) {
      if (d.afterBusinessType.length === 1 && d.afterBusinessType.includes(code)) {
        return true
      }
      return false
    }
  }
}
</script>
<style lang="scss" scoped>
.change-table-title{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  &>span{
    color: #333;
    font-size: 16px;
    font-weight: 600;
    margin-right: 10px;
  }
}
  .template-down{
    // display: flex;
    // align-content: center;
    display: inline-block;
    cursor: pointer;
    &>*{
      margin-right: 10px;
      color: #333;
      font-weight: 600;
    }
  }
</style>
